package com.dao.generic;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.dao.exception.DAOException;
import com.dao.factory.ConnectionFactory;

public abstract class GenericDAO {

	private Connection conn;
	private PreparedStatement pstm;

	protected void adicionar(String sql, Object... 
			parametros) throws DAOException {
		try {
			conn = ConnectionFactory.getConnection();
			pstm = conn.prepareStatement(sql);
			for (int i = 0; i < parametros.length; i++) {
				pstm.setObject(i + 1, parametros[i]);
			}
			pstm.execute();
		} catch (SQLException e) {
			throw new DAOException(e.getMessage(), e.getCause());
		} finally {
			ConnectionFactory.closeConnection(conn, pstm);
		}
	}

	protected void atualizar(String sql, int id, Object...
			parametros) throws DAOException {
		try {
			conn = ConnectionFactory.getConnection();
			pstm = conn.prepareStatement(sql);
			for (int i = 0; i < parametros.length; i++) {
				pstm.setObject(i + 1, parametros[i]);
			}
			pstm.setObject(parametros.length + 1, id);
			pstm.execute();
		} catch (SQLException e) {
			throw new DAOException(e.getMessage(), e.getCause());
		} finally {
			ConnectionFactory.closeConnection(conn, pstm);
		}
	}

	protected void excluir(String sql, Object... 
			parametros) throws DAOException {
		try {
			conn = ConnectionFactory.getConnection();
			pstm = conn.prepareStatement(sql);
			for (int i = 0; i < parametros.length; i++) {
				pstm.setObject(i + 1, parametros[i]);
			}
			pstm.execute();
		} catch (SQLException e) {
			throw new DAOException(e.getMessage(), e.getCause());
		} finally {
			ConnectionFactory.closeConnection(conn, pstm);
		}
	}
}